# -*- coding:utf-8 -*-
#2022/1/10 10:41
# author:xwl
import math
import traceback

from fastapi import APIRouter, Depends

from backend.app.app.api.api_Hu.crud.pro.tb_userpro_input import get_projId_by_user_id, read_pri_well, query_oil, \
    query_ratio, oilsalecost_ratio, oilprodcost, deletefun
from backend.app.app.api.api_Xiong.crud.pub_crud import addwell_function, read_db_all_well
from backend.app.app.api.api_Xiong.models.x_model import input_data, calculation_data
from backend.app.app.api.api_v1.user import verify_token_user
from backend.app.app.api.calculation.evaluation_calculation import wellOprCost, grossSalesIncome, totalTax, staticGains, \
    staticGainsPy, evaluation_calculation5, evaluation_calculation6, evaluation_calculation7, evaluation_calculation8, \
    evaluation_calculation9, evaluation_calculation10
from backend.app.app.crud_pub.well_input import well_input_add
from backend.app.app.models.project import user_id, input_well_query_require

well_input_route = APIRouter(prefix="/well_input_data", tags=["单井输入数据"])

@well_input_route.post("get_pro_id",name="获取用户最新的project_id")
async def get_pro_id(id: user_id, ver = Depends(verify_token_user)):
    input_project_inf, out_project_inf = get_projId_by_user_id(user_id=id.user_id)
    input_proj_data=set()
    out_proj_data=set()
    if input_project_inf:
        for inf in input_project_inf:
            input_proj_data.add(inf[0])
    if out_project_inf:
        for inf in out_project_inf:
            out_proj_data.add(inf[0])
    project_id=input_proj_data&out_proj_data
    return {"user_id":id.user_id,"project_id":project_id,"verify":ver}

@well_input_route.post("/read_lib",name="读库之后查询")
async def read_lib(query_criteria: input_well_query_require, ver = Depends(verify_token_user)):
    query_result = read_pri_well(query_criteria.well_name, query_criteria.type, query_criteria.start_year, query_criteria.end_year)
    oil_inf = query_oil(query_criteria.well_name, start_year=query_criteria.start_year[:4],
                        end_year=query_criteria.end_year[:4])
    ratio_inf = query_ratio(query_criteria.well_name, start_year=query_criteria.start_year[:4],
                            end_year=query_criteria.end_year[:4])
    return {"query_result": query_result, "oil_info": oil_inf, "ratio_info": ratio_inf, "verify":ver}

@well_input_route.post("/save_lib",name="存库")
async def save_lib(inputdata:input_data, ver=Depends(verify_token_user)):
    delete_result = deletefun(inputdata.delete)
    result = well_input_add(inputdata.data)
    ratio = oilsalecost_ratio(inputdata.ratio)
    oilcost = oilprodcost(inputdata.oilcost)
    return {
        'result': result,
        'oilcost': oilcost,
        'ratio': ratio,
        'delete_result': delete_result,
        'verify': ver
    }

@well_input_route.post("/calculation",name="计算")
async def calculation(datas:calculation_data, ver=Depends(verify_token_user)):
    result=[]
    try:
        temp1=dict()
        for data in datas.cal_data:
            # 1.计算平均增油操作成本
            WellOprCost = wellOprCost(IncreOil=float(data["Stim_IncreOil"]), OilOprCost=float(data["Oil_OprCost"]))

            # 2.计算平均增油毛收入
            GrossSalesIncome = grossSalesIncome(OilPrice=float(data["Oil_Price"]), OilCommodityRatio=float(data["Oil_CommodityRatio"]),
                                                IncreOil=float(data["Stim_IncreOil"]))

            # 3.计算平均销售税费
            TotalTax = totalTax(GrossSalesIncome=GrossSalesIncome, TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]))

            # 4.平均静态收益（元/井）：StaticGains
            StaticGains = staticGains(StimCost=float(data["Stim_Cost"]), WellOprCost=WellOprCost, TotalTax=TotalTax,
                                      GrossSalesIncome=GrossSalesIncome)

            # 5.平均财务净现值（元/井）：StimNPV
            # ValidPeriod = 123 #有效天  未找到，临时使用
            # 直接计算StaticGainsPy, 后续需要使用
            ValidPeriod = int(float(data["Stim_ValidPeriod"]))
            if ValidPeriod <=0:
                return {
                    'error': '有效天数不能为小于等于0'
                }
            ValidYears = math.ceil(ValidPeriod / 365)
            ic = float(data["Money_Discount"]) / 100
            StaticGainsPy_by_count = staticGainsPy(IncreOil=float(data["Stim_IncreOil"]), ValidYears=ValidYears,
                                                   OilPrice=float(data["Oil_Price"]), OilCommodityRatio=float(data["Oil_CommodityRatio"]),
                                                   TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]), OilOprCost=float(data["Oil_OprCost"]))
            StimNPV = evaluation_calculation5(ValidYears=ValidYears, StaticGainsPy=StaticGainsPy_by_count, ic=ic,
                                              StimCost=float(data["Stim_Cost"]))
            # 6.投资利润率（%）：StimROI
            StimROI = evaluation_calculation6(StaticGains=StaticGains, StimCost=float(data["Stim_Cost"]))
            print("6True")
            # 7.财务净现值率（%）：
            StimNPVR = evaluation_calculation7(StimNPV=StimNPV, StimCost=float(data["Stim_Cost"]))
            print("7True")
            # 8.财务内部收益率（%）：StimFIRR
            # ValidPeriod = data["Stim_ValidPeriod_Average"]
            # ValidYears = math.ceil(ValidPeriod / 365)
            StimFIRR = evaluation_calculation8(ValidYears=ValidYears, StimCost=float(data["Stim_Cost"]),
                                               StaticGainsPy=StaticGainsPy_by_count)
            print("8True")
            # 9.平均经济临界增油量（吨/井）：IncreOilCritical
            # ic = data["Money_Discount"]/100
            IncreOilCritical = evaluation_calculation9(ValidYears=ValidYears, ic=ic, StimCost=float(data["Stim_Cost"]),
                                                       OilPrice=float(data["Oil_Price"]), OilOprCost=float(data["Oil_OprCost"]),
                                                       OilCommodityRatio=float(data["Oil_CommodityRatio"]),
                                                       TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]))
            # 10.平均经济临界油价（元/吨）：OilPriceCritical
            increOilPy = float(data["Stim_IncreOil"]) / ValidYears
            OilPriceCritical = evaluation_calculation10(ValidYears=ValidYears, ic=ic, StimCost=float(data["Stim_Cost"]),
                                                        IncreOilPy=increOilPy, OilOprCost=float(data["Oil_OprCost"]),
                                                        OilCommodityRatio=float(data["Oil_CommodityRatio"]),
                                                        TotalTaxRatio=float(data["OilSale_TotalTaxRatio"]))
            # 把所有处理完的数据添加到结果
            temp1 = {
                "User_ID": data['User_ID'],
                "Proj_ID": data['Proj_ID'],
                'Well_Name': data['Well_Name'],
                'DvpUnit_Name': data['DvpUnit_Name'],
                'Stim_Date': data['Stim_Date'],
                'StimType_Name': data['StimType_Name'],
                'Stim_ValidPeriod': data['Stim_ValidPeriod'],
                'Stim_IncreOil': data['Stim_IncreOil'],
                'Stim_Cost': data['Stim_Cost'],
                'Oil_CommodityRatio': data['Oil_CommodityRatio'],
                'Oil_Price': data['Oil_Price'],
                'Oil_OprCost': data['Oil_OprCost'],
                'OilSale_TotalTaxRatio': data['OilSale_TotalTaxRatio'],
                'Money_Discount': data['Money_Discount'],
                'Remark':data['Remark'],
                "WellOprCost": WellOprCost,
                "TotalTax": TotalTax,
                "GrossSalesIncome": GrossSalesIncome,
                "StaticGains": StaticGains,
                "StimNPV": StimNPV,
                "StimROI": StimROI,
                "StimNPVR": StimNPVR,
                "StimFIRR": StimFIRR,
                "IncreOilCritical": IncreOilCritical,
                "OilPriceCritical": OilPriceCritical
            }
            result.append(temp1)
        return {
            'result': result if result else {},
            'verify': ver
        }
    except Exception as e:
        print(traceback.print_exc())

@well_input_route.post("/addwell",name="AddWell")
async def addwell(Well_Name:str, Belong_DvpUnit_Name:str, Remark:str=None, GeoCoordX:float=None, GeoCoordY:float=None,
                  ver=Depends(verify_token_user)):
    result = addwell_function(Well_Name, GeoCoordX, GeoCoordY, Belong_DvpUnit_Name,Remark)
    return{
        'result':result,
        'verify': ver
    }

@well_input_route.post("/read_all_well",name="读所有井号")
async def read_all_well(ver=Depends(verify_token_user)):
    result=read_db_all_well()
    return{
        'result':result,
        'verify': ver
    }